package cn.com.mall.search.service.impl;

import cn.com.mall.common.dto.es.SkuEsModel;
import cn.com.mall.search.constant.EsConstant;
import cn.com.mall.search.service.SearchService;
import cn.com.mall.search.vo.SearchParam;
import cn.com.mall.search.vo.SearchResult;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.*;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    RestHighLevelClient restHighLevelClient;

    @Override
    public SearchResult search(SearchParam searchParam) {

        SearchResult result=null;
        SearchRequest searchRequest=builderSearchRequest(searchParam);

        try {
            SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            result=buildSearchResult(searchParam,searchResponse);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }

    private SearchResult buildSearchResult(SearchParam searchParam,SearchResponse searchResponse) {
        SearchResult searchResult=new SearchResult();

        SearchHits hits = searchResponse.getHits();
        //返回查询到的所有商品
        SearchHit[] hitsArray = hits.getHits();
        if(hits!=null && hitsArray.length>0) {
            List<SkuEsModel> skuEsModelList = Arrays.stream(hitsArray).map(
                    item -> {
                        String sourceAsString = item.getSourceAsString();
                        try {
                            SkuEsModel skuEsModel = new ObjectMapper().readValue(sourceAsString, SkuEsModel.class);
                            //skutitle应该从高亮中进行获取
                            if(!StringUtils.isEmpty(searchParam.getKeyword())){
                                String skuTitle = item.getHighlightFields().get("skuTitle").getFragments()[0].toString();
                                skuEsModel.setSkuTitle(skuTitle);
                            }
                            return skuEsModel;
                        } catch (JsonProcessingException e) {
                            e.printStackTrace();
                        }
                        return new SkuEsModel();
                    }
            ).collect(Collectors.toList());
            searchResult.setProduct(skuEsModelList);
        }



        Aggregations aggregations = searchResponse.getAggregations();
        //当前商品涉及到的所有属性信息
        ParsedNested attrs_agg=aggregations.get("attrs_agg");
        ParsedLongTerms attr_id_agg = attrs_agg.getAggregations().get("attr_id_agg");
        List<SearchResult.AttrVo> attrVoList = attr_id_agg.getBuckets().stream().map(
                item -> {
                    SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
                    item.getAggregations();

                    attrVo.setAttrId(Long.parseLong(item.getKeyAsString()));
                    ParsedStringTerms attr_name_agg = item.getAggregations().get("attr_name_agg");
                    attrVo.setAttrName(attr_name_agg.getBuckets().get(0).getKeyAsString());
                    ParsedStringTerms attr_value_agg = item.getAggregations().get("attr_value_agg");
                    List<String> stringList = attr_value_agg.getBuckets().stream().map(
                            attr_value -> attr_value.getKeyAsString()
                    ).collect(Collectors.toList());
                    attrVo.setAttrValue(stringList);

                    return attrVo;
                }
        ).collect(Collectors.toList());
        searchResult.setAttrs(attrVoList);

        //品牌信息
        ParsedLongTerms brand_agg = aggregations.get("brand_agg");
        List<SearchResult.BrandVo> brandVoList = brand_agg.getBuckets().stream().map(
                item -> {
                    SearchResult.BrandVo brandVo = new SearchResult.BrandVo();

                    Long brandId = Long.parseLong(item.getKeyAsString());
                    brandVo.setBrandId(brandId);

                    ParsedStringTerms brand_name_agg = item.getAggregations().get("brand_name_agg");
                    brandVo.setBrandName(brand_name_agg.getBuckets().get(0).getKeyAsString());


                    ParsedStringTerms brand_img_agg = item.getAggregations().get("brand_img_agg");
                    brandVo.setBrandImg(brand_img_agg.getBuckets().get(0).getKeyAsString());

                    return brandVo;
                }
        ).collect(Collectors.toList());

        searchResult.setBrands(brandVoList);

        //分类信息
        ParsedLongTerms catelog_agg = aggregations.get("catelog_agg");

        List<SearchResult.CatalogVo> catalogVoList = catelog_agg.getBuckets().stream().map(
                item->{
                    SearchResult.CatalogVo catalogVo=new SearchResult.CatalogVo();

                    //得到分类的名字
                    ParsedStringTerms catelog_name_agg = item.getAggregations().get("catelog_name_agg");
                    String catalogName = catelog_name_agg.getBuckets().get(0).getKeyAsString();

                    catalogVo.setCatalogId(Long.parseLong(item.getKeyAsString()));
                    catalogVo.setCatalogName(catalogName);
                    return catalogVo;

                }
        ).collect(Collectors.toList());

        searchResult.setCatalogs(catalogVoList);

        //页码
        searchResult.setPageNum(searchParam.getPageNum());

        long total=hits.getTotalHits().value;
        //总记录数
        searchResult.setTotal(total);
        int pagesize=total%EsConstant.PRODUCT_PAGESIZE==0?(int) total/EsConstant.PRODUCT_PAGESIZE:(int)((total/EsConstant.PRODUCT_PAGESIZE)+1);
        //总页码
        searchResult.setTotalPages(pagesize);
        System.out.println(searchResult.toString());
        return searchResult;
    }

    /**
     * 准备检索请求
     * @param searchParam
     * @return
     */
    private SearchRequest builderSearchRequest(SearchParam searchParam) {

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        //1.1 must模糊匹配
       /* "must": [
        {
            "match": {
            "skuTitle": "apple"
        }
        }
      ],
       */
        String keyword = searchParam.getKeyword();
        if(!StringUtils.isEmpty(keyword)){
            MatchQueryBuilder skuTitle = QueryBuilders.matchQuery("skuTitle", keyword);
            boolQueryBuilder.must(skuTitle);
        }
        //1。2、 bool -filter 按照三级分配id查询
        /*"filter": [
        {
            "term": {
            "catelogId": 225
        }
        },*/
        Long catalog3Id = searchParam.getCatalog3Id();
        if(catalog3Id!=null){
            TermQueryBuilder catelogId = QueryBuilders.termQuery("catelogId", catalog3Id);
            boolQueryBuilder.filter(catelogId);
        }

        //1。3、bool --filter  按照品牌id查询
        List<Long> brandId = searchParam.getBrandId();
        if(brandId!=null && brandId.size()>0){
            TermsQueryBuilder brandId1 = QueryBuilders.termsQuery("brandId", brandId);
            boolQueryBuilder.filter(brandId1);
        }

        //1。3、bool --filter  按照属性查询
        List<String> attrs = searchParam.getAttrs();
        if(attrs!=null && attrs.size()>0){
            // attrs=1_5寸:6寸&attrs=2_16G:64G

            for (String attrStr : attrs) {
                BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
                String[] s = attrStr.split("_");
                String attrId=s[0];
                String[] attrValues = s[1].split(":");

                queryBuilder.must(QueryBuilders.termQuery("attrs.attrId",attrId));
                queryBuilder.must(QueryBuilders.termsQuery("attrs.attrValue",attrValues));
               //每一个必须都要生成一个nested查询
                NestedQueryBuilder nestedQueryBuilder = QueryBuilders.nestedQuery("attrs", queryBuilder, ScoreMode.None);
                boolQueryBuilder.filter(nestedQueryBuilder);
            }

        }
//bool --filter  按照是否有库存
        Integer hasStock = searchParam.getHasStock();
        if(hasStock!=null ){
            boolQueryBuilder.filter(QueryBuilders.termQuery("hosStock",hasStock==1));
        }

        //价格区间
        String skuPrice = searchParam.getSkuPrice();
        if(!StringUtils.isEmpty(skuPrice)){
            RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("skuPrice");
            String[] s = skuPrice.split("_");
            if(s.length==2){
                rangeQueryBuilder.lte(s[1]);
                rangeQueryBuilder.gte(s[0]);
            }else if(s.length==1){
                if(skuPrice.startsWith("_")){
                    rangeQueryBuilder.lte(s[0]);
                }else{
                    rangeQueryBuilder.gte(s[0]);

                }
            }

            boolQueryBuilder.filter(rangeQueryBuilder);
        }


        searchSourceBuilder.query(boolQueryBuilder);

        /**
         * 聚合分析
         */

        //品牌的聚合
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg");
        brand_agg.field("brandId").size(50);
        //子聚合
        TermsAggregationBuilder brand_name_agg = AggregationBuilders.terms("brand_name_agg").field("brandName").size(1);
        brand_agg.subAggregation(brand_name_agg);

        TermsAggregationBuilder brand_img_agg = AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1);
        brand_agg.subAggregation(brand_img_agg);
        searchSourceBuilder.aggregation(brand_agg);

        // 分类的聚合
        TermsAggregationBuilder catelog_agg = AggregationBuilders.terms("catelog_agg").field("catelogId").size(20);
        TermsAggregationBuilder  catelog_name_agg= AggregationBuilders.terms("catelog_name_agg").field("catalogName").size(1);
        catelog_agg.subAggregation(catelog_name_agg);
        searchSourceBuilder.aggregation(catelog_agg);

        //属性聚合
        NestedAggregationBuilder attrs_agg=AggregationBuilders.nested("attrs_agg","attrs");

        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId").size(50);
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(50));

        attrs_agg.subAggregation(attr_id_agg);
        searchSourceBuilder.aggregation(attrs_agg);


        //排序、分页

        String sort=searchParam.getSort();
        if(!StringUtils.isEmpty(sort)){
            String[] s = sort.split("_");
            searchSourceBuilder.sort(s[0],s[1].equalsIgnoreCase("asc")? SortOrder.ASC:SortOrder.DESC);
        }

        //分页 from=(pageNum -1) * size
        searchSourceBuilder.from((searchParam.getPageNum()-1)*EsConstant.PRODUCT_PAGESIZE);
        searchSourceBuilder.size(EsConstant.PRODUCT_PAGESIZE);

        //高亮
        if(!StringUtils.isEmpty(keyword)){
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");
            searchSourceBuilder.highlighter(highlightBuilder);
        }
        System.out.println(searchSourceBuilder.toString());

        return  new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX},searchSourceBuilder);
    }
}
